package timers

import (
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/storage/database"
	"gitee.com/mootok/mootok/src/storage/file"
	log "github.com/sirupsen/logrus"
	"time"
)

func cleanUploadTasksTimer(duration time.Duration) {
	ticker := time.NewTicker(duration)
	quit := make(chan struct{})
	go func() {
		for {
			select {
			case <-ticker.C:
				log.Println("Clearing expired tasks...")
				var tasks []models.UploadTask
				database.Client.Find(&tasks, "expired_at < ?", time.Now().Unix())
				if len(tasks) == 0 {
					log.Printf("No expired tasks.")
					continue
				}
				fileNames := make([]string, len(tasks))
				for i, task := range tasks {
					fileNames[i] = task.FileName
				}
				go func() {
					_, err := file.Instance.BatchDelete(fileNames)
					if err != nil {
						log.Errorf("Failed batch delete: %s", err)
					}
				}()
				database.Client.Delete(tasks)
				log.Printf("Removed %d expired tasks.", len(tasks))

			case <-quit:
				ticker.Stop()
				return
			}
		}
	}()
}